import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import type { ElementPlusSize } from '@/types/elementPlus'
import type { ThemeTypes } from '@/types/theme'
import { humpToUnderline, setCssVar } from '@/utils'
import { getCssColorVariable, hexToRGB, mix } from '@/utils/color'
import { defineStore } from 'pinia'
import { store } from '../index'
import type { LayoutType } from '@/types/layout'

const { wsCache } = useCache()

interface AppState {
  pageLoading: boolean
  title: string
  isDark: boolean
  currentSize: ElementPlusSize
  sizeMap: ElementPlusSize[]
  theme: ThemeTypes
  greyMode: false // 是否开始灰色模式，用于特殊悼念日
  layout: LayoutType
}

export const useAppStore = defineStore('app', {
  state: (): AppState => {
    return {
      pageLoading: false,
      title: import.meta.env.VITE_APP_TITLE,
      currentSize: wsCache.get('default') || 'default', // 组件尺寸,
      sizeMap: ['default', 'large', 'small'],
      isDark: wsCache.get(CACHE_KEY.IS_DARK) || false, // 是否是暗黑模式
      theme: wsCache.get(CACHE_KEY.THEME) || {
        elColorPrimary: '#409EFF',
      },
      greyMode: false,
      layout: wsCache.get(CACHE_KEY.LAYOUT) || 'layout',
    }
  },
  getters: {
    getCurrentSize(): ElementPlusSize {
      return this.currentSize
    },
    getSizeMap(): ElementPlusSize[] {
      return this.sizeMap
    },
    getIsDark(): boolean {
      return this.isDark
    },
    getTheme(): ThemeTypes {
      return this.theme
    },
    getGreyMode(): boolean {
      return this.greyMode
    },
    getLayout(): LayoutType {
      return this.layout
    },
    getPageLoading(): boolean {
      return this.pageLoading
    },
    getTitle(): string {
      return this.title
    },
  },
  actions: {
    setPrimaryLight() {
      if (this.theme.elColorPrimary) {
        const elColorPrimary = this.theme.elColorPrimary
        const color = this.isDark ? '#000000' : '#ffffff'
        const lightList = [3, 5, 7, 8, 9]
        lightList.forEach(v => {
          setCssVar(
            `--el-color-primary-light-${v}`,
            mix(color, elColorPrimary, v / 10)
          )
        })
        setCssVar(`--el-color-primary-dark-2`, mix(color, elColorPrimary, 0.2))

        this.setAllColorRgbVars()
      }
    },
    // 处理element自带的主题色和辅助色的-rgb切换主题变化，如：--el-color-primary-rgb
    setAllColorRgbVars() {
      // 需要处理的颜色类型列表
      const colorTypes = [
        'primary',
        'success',
        'warning',
        'danger',
        'error',
        'info',
      ]

      colorTypes.forEach(type => {
        // 获取当前颜色值
        const colorValue = getCssColorVariable(`--el-color-${type}`)
        if (colorValue) {
          // 转换为rgba并提取RGB部分
          const rgbaString = hexToRGB(colorValue, 1)
          const rgbValues = rgbaString.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/i)
          if (rgbValues) {
            const [, r, g, b] = rgbValues
            // 设置对应的RGB变量
            setCssVar(`--el-color-${type}-rgb`, `${r}, ${g}, ${b}`)
          }
        }
      })
    },
    setTitle(title: string) {
      this.title = title
    },
    setIsDark(isDark: boolean) {
      this.isDark = isDark
      if (this.isDark) {
        document.documentElement.classList.add('dark')
        document.documentElement.classList.remove('light')
      } else {
        document.documentElement.classList.add('light')
        document.documentElement.classList.remove('dark')
      }
      wsCache.set(CACHE_KEY.IS_DARK, this.isDark)
      this.setPrimaryLight()
    },
    setCurrentSize(currentSize: ElementPlusSize) {
      this.currentSize = currentSize
      wsCache.set('currentSize', this.currentSize)
    },
    setTheme(theme: ThemeTypes) {
      this.theme = Object.assign(this.theme, theme)
      wsCache.set(CACHE_KEY.THEME, this.theme)
    },
    setCssVarTheme() {
      for (const key in this.theme) {
        setCssVar(`--${humpToUnderline(key)}`, this.theme[key])
      }
      this.setPrimaryLight()
    },
    setLayout(layout: LayoutType) {
      this.layout = layout
      wsCache.set(CACHE_KEY.LAYOUT, this.layout)
    },
  },
  persist: false,
})

export const useAppStoreWithOut = () => {
  return useAppStore(store)
}
